package com.springboot.frame.oauth.server.controller;

import com.springboot.frame.oauth.server.dto.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.AuthorizationRequest;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.Map;


/**
 * @author liheng
 * @ClassName Oauth2Controller
 * @Description
 * @date 2020-04-25 22:05
 */
@Controller
// 必须配置
@SessionAttributes("authorizationRequest")
public class Oauth2Controller {
    @Autowired
    private HttpServletRequest httpServletRequest;

    /**
     * 首页
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("/index")
    public ModelAndView index() {
        ModelAndView view = new ModelAndView();
        view.setViewName("index");
        view.addObject("name", "Security oauth2.0");
        return view;
    }


    /**
     * 自定义授权页
     *
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping("/confirm_access")
    public ModelAndView getAccessConfirmation(Map<String, Object> model) {
        AuthorizationRequest authorizationRequest = (AuthorizationRequest) model.get("authorizationRequest");
        ModelAndView view = new ModelAndView();
        view.setViewName("grant");
        view.addObject("clientId", authorizationRequest.getClientId());
        view.addObject("scopes", authorizationRequest.getScope());
        return view;
    }


    /**
     * 登陆后进行授权码授权
     *
     * @param dto
     * @return java.lang.String
     * @author liheng
     * @date 2022-03-18 17:34
     */
    @PostMapping("/grant")
    public String grant(@RequestBody OauthGrantDto dto) {
        return "redirect:" + httpServletRequest.getContextPath() + "/oauth/authorize?response_type=code"
                + "&client_id=" + dto.getClient_id() + "&redirect_uri=" + dto.getRedirect_uri() + "&scope=" + dto.getScope();
    }


//  /**
//   * Oauth2密码模式授权
//   * @author liheng
//   * @date 2022-03-18 17:34
//   * @param dto
//   * @return java.lang.String
//   */
//    @PostMapping("/oauth2.0/pass")
//    @ResponseBody
//    public String oauthPass(@RequestBody OauthPassDto dto) {
//        RestTemplate restTemplate = new RestTemplate();
//        HttpEntity<OauthPassDto> entity = new HttpEntity<>(dto);
//        String result = restTemplate.exchange(httpServletRequest.getContextPath() + "/oauth/token", HttpMethod.POST, entity, String.class).getBody();
//        return result;
//    }
//
//   /**
//    * Oauth2 授权码模式获取token
//    * @author liheng
//    * @date 2022-03-18 17:34
//    * @param dto
//    * @return java.lang.String
//    */
//    @PostMapping("/oauth2.0/code")
//    @ResponseBody
//    public String oauthCode(@RequestBody OauthCodeDto dto) {
//        RestTemplate restTemplate = new RestTemplate();
//        HttpEntity<OauthCodeDto> entity = new HttpEntity<>(dto);
//        StringBuffer url = httpServletRequest.getRequestURL();
//        String tempContextUrl = url.delete(url.length() - httpServletRequest.getRequestURI().length(), url.length()).append(httpServletRequest.getSession().getServletContext().getContextPath()).append("/").toString();
//        System.out.println(tempContextUrl);
//        String result = restTemplate.exchange(tempContextUrl + "/oauth/token", HttpMethod.POST, entity, String.class).getBody();
//        return result;
//    }
//
//    /**
//     * Oauth2 简单模式授权  直接用请求地址在浏览器上访问就行  端点映射不生效，不能使用oauth2.0  其他模式均可\n" +
//     *   示例： http://localhost:8085/oauth/authorize?response_type=token&client_id=janche&redirect_uri=https://janche.github.io&scope=all
//     * @author liheng
//     * @date 2022-03-18 17:34
//     * @param dto
//     * @return java.lang.String
//     */
//    @PostMapping("/oauth2.0/simple")
//    public String oauthToken(@RequestBody OauthTokenDto dto) {
//        return "redirect:" + httpServletRequest.getContextPath() + "/oauth/token?response_type=token"
//                + "&client_id=" + dto.getClient_id() + "&redirect_uri=" + dto.getRedirect_uri() + "&scope=" + dto.getScope();
//    }
//
//
//   /**
//    * Oauth2 客户端模式
//    * @author liheng
//    * @date 2022-03-18 17:35
//    * @param dto
//    * @return java.lang.String
//    */
//    @PostMapping("/oauth2.0/client")
//    @ResponseBody
//    public String oauthClient(@RequestBody OauthClientDto dto) {
//        RestTemplate restTemplate = new RestTemplate();
//        HttpEntity<OauthClientDto> entity = new HttpEntity<>(dto);
//        StringBuffer url = httpServletRequest.getRequestURL();
//        String tempContextUrl = url.delete(url.length() - httpServletRequest.getRequestURI().length(), url.length()).append(httpServletRequest.getSession().getServletContext().getContextPath()).append("/").toString();
//        System.out.println(tempContextUrl);
//        String result = restTemplate.exchange(tempContextUrl + "/oauth/token", HttpMethod.POST, entity, String.class).getBody();
//        return result;
//    }
//
//
//    /**
//     * refresh token 刷新token
//     * @author liheng
//     * @date 2022-03-18 17:35
//     * @param dto
//     * @return java.lang.String
//     */
//    @PostMapping("/oauth2.0/token")
//    @ResponseBody
//    public String refreshToken(@RequestBody RefreshTokenDto dto) {
//        RestTemplate restTemplate = new RestTemplate();
//        HttpEntity<RefreshTokenDto> entity = new HttpEntity<>(dto);
//        String result = restTemplate.exchange(httpServletRequest.getContextPath() + "/oauth/token", HttpMethod.POST, entity, String.class).getBody();
//        return result;
//    }


    /**
     * Principal 中的对象需要序列化，否则无法获取
     * <p>
     * <p>
     * *******************开放给oauth客户端使用的接口 *******************
     */
    @ResponseBody
    @GetMapping("/userinfo")
    public Object getUserinfo() {
        OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) SecurityContextHolder.getContext().getAuthentication();
        // 获取当前登录用户的详细信息
        return oAuth2Authentication.getPrincipal();
    }

    /**
     * Principal 中的对象需要序列化，否则无法获取
     * <p>
     * <p>
     * *******************开放给oauth客户端使用的接口 *******************
     */
    @ResponseBody
    @GetMapping("/all")
    public Object getAll() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        // 获取当前登录用户的详细信息
        return authentication.getPrincipal();
    }
}
